/*
 * DA3.c

This is design assignment 3 for cpe301 spring 2015 at UNLV

The goal of this assignment is to read the temperature from the LM34 temperature sensor
using an ADC and output the reading in Fahrenheit to a serial terminal. An FTDI chip
will be used to convert the USART communication to USB. A timer will be used to generate
an interrupt to display the temperature in one second intervals.

 */ 

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>

volatile unsigned int adc_temp;
char outs[20];

void usart_init (void)
{
	UCSR0B 	= 	(1<<TXEN0);					//enable transmit
	UCSR0C 	= 	((1<<UCSZ01)|(1<<UCSZ00));	//asynchronous mode 8b data 8MHz clk
	UBRR0 	= 	0x33;						//set baud rate to 9600
}
void USART_tx_string (char *data)
{
	while((*data!='\0')){
		while(!(UCSR0A&(1<<UDRE0)));			//wait until transmit register is empty
		UDR0 = *data;
		data++;
	}
}
ISR(TIMER1_OVF_vect){
	adc_temp = ADC*110/1024+'0';
	snprintf(outs,sizeof(outs),"%3d Fahrenheit\r\n",adc_temp);
	USART_tx_string(outs);
	
	TCNT1= 0x85EE;
	//TIFR1= (1<<TOV1);
}

int main(void)
{
	//SET ADC
	//USE ADC0, AREF, FREE RUNNING
	ADMUX = 0x00;
	ADCSRB = 0x00;
	ADCSRA = (1<<ADEN) | (1<<ADSC);
	
	//ENABLE INTERRUPT
	TIMSK1 |= (1<<TOIE1);
	sei();
	
	//SET TIMER
	//TIMER1, NORMAL MODE, 256 prescaler
	//1 second interval
	TCNT1 = 0x85EE;
	TCCR1A = 0x00;
	TCCR1B |= (1<<CS12);
	
	usart_init();
	while(1)
	{
	}
	return 0;
}